//
//  MainTabBar.swift
//  weibo
//
//  Created by William Peng on 16/3/20.
//  Copyright © 2016年 William Peng. All rights reserved.
//

import UIKit

//设置tabBarItem的个数
let TabBarItemCount = 5

class MainTabBar: UITabBar {

    override func layoutSubviews() {
        super.layoutSubviews()
        
       
        
        //计算 item的宽度 : tabBar宽度 / item个数
        let width = frame.width / (CGFloat)(TabBarItemCount)
        
        //计算最左边的frame 然后CGRectOffset(偏移值)
        let originFrame = CGRect(x: 0, y: 0, width: width, height: frame.height)
        
        //起始item的index值
        var index = 0
        
        for view in subviews{
            
            //判断是否UITabBarButton
            let cfs = NSClassFromString("UITabBarButton")
            if view.isKindOfClass(cfs!){
                
                //设置每个UITabBarButton的位置
                //rect:原始frame值
                //dx:x方向的偏移值 **item个数 对应宽度
                //dy:y方向的偏移值
                view.frame = CGRectOffset(originFrame, (CGFloat)(index) * width, 0)
                
                index += index == 1 ? 2 : 1
            }
        }
        
        //设置加号按钮的frame
        centerButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.height)
    }
    //懒加载 加号按钮
    private lazy var centerButton: UIButton = {
        
        let button = UIButton()
        
        //设置button背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //设置button的图标
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        //添加到tabBar上
        self.addSubview(button)
        
        return button
    }()

}
